package cn.com.yto56.coresystem.business.msg.web.controller;

import cn.com.yto56.coresystem.business.msg.web.biz.IYtoMsgBiz;
import cn.com.yto56.coresystem.common.msg.util.base.StringUtils;
import cn.com.yto56.coresystem.common.msg.util.data.DataTypeChangeTool;
import cn.com.yto56.coresystem.common.msg.util.domain.AppResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Handler处理类
 * Created by wangrui on 2017/6/5.
 */
public class YtoMsgWebSocketHandler extends TextWebSocketHandler {
    private final static Logger logger = LoggerFactory.getLogger(YtoMsgWebSocketHandler.class);
    public final static List<WebSocketSession> sessions = Collections.synchronizedList(new ArrayList<WebSocketSession>());

    public IYtoMsgBiz ytoMsgBizImpl;

    public YtoMsgWebSocketHandler(IYtoMsgBiz ytoMsgBizImpl) {
        this.ytoMsgBizImpl = ytoMsgBizImpl;
    }

    /**
     * 接收文本消息，并发送出去
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        String requstMsg = message.getPayload();
        Map map = DataTypeChangeTool.jsonToMap(requstMsg);
        String userId = (String) map.get("yto_msg_userId");
        String appId = (String) map.get("yto_msg_appId");
        String interfaceName = (String) map.get("interfaceName");
        session.getAttributes().put("yto_msg_appId", appId);
        session.getAttributes().put("yto_msg_userId", userId);
        if (StringUtils.isNotBlank(interfaceName) && interfaceName.equals("modifyMsgState")) {
            List msgIds = (List) map.get("msgIds");
            AppResult appResult = ytoMsgBizImpl.modifyMsgState(appId, userId, msgIds);
            TextMessage returnMessage = new TextMessage(DataTypeChangeTool.beanToJSON(appResult));
            session.sendMessage(returnMessage);
        }
    }

    //连接建立后处理
    @SuppressWarnings("unchecked")
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        //处理离线消息
    }

    //抛出异常时处理
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        logger.debug("websocket chat connection closed......");
        sessions.remove(session);
    }

    //连接关闭后处理
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        logger.debug("websocket chat connection closed......");
        sessions.remove(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
